<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2020 All rights reserved.
// +----------------------------------------------------------------------
// | User: Simony <1362229026@qq.com>
// | wechat: Shen86579595
// +----------------------------------------------------------------------

namespace app\common\logic\member;

use think\facade\Cache;

class TokenLogic
{
    public $login_expire = 3600 * 24 * 30; //一个月免登陆
    public $generation_time = 3600; //更新操作时间
    public $platform = 'unified';

    /***
     * User:Simony
     * Function: 生成token
     * @param $token token存在就更新，不存在创建  保持缓存
     * @param $member_id
     * @param $mobile
     * @return mixed
     */
    public function getToken($platform, $mobile, $timestamp)
    {
        if (is_null($platform)) $platform = $this->platform;
        //model
        $memberModel = model('common/member/Member');
        $tokenModel = model('common/member/Token');

        //getData
        $field = 'id, username, avatar, nickname, sex, province, city, district, birthday,level,invite_code,status, real_verify, video_verify, recommend_str, recommend_dept, recommend_num';
        $member = $memberModel->getInfo(['username' => $mobile], $field); //会员数据
        $member = $member->toArray();
        $dbToken = $tokenModel->getInfo(['member_id' => $member['id'], 'platform' => $platform]); //token数据

        $token = $this->createTokenVal($mobile);

        $generation_time =  $timestamp + $this->generation_time;
        $data = [
            'token' => $token,
            'generation_time' => $generation_time,
            'expire_time' => $timestamp + $this->login_expire,
            'data' => json_encode(array_merge($member, ['generation_time' => $generation_time, 'expire_time' => $timestamp + $this->login_expire]))
        ];

        if (empty($dbToken)) { //不存在生成
            $data['platform'] = $platform;
            $data['member_id'] = $member['id'];
            $tokenModel->add($data);
        } else {
            \cache($platform . '-' . $dbToken['token'], null);
            $tokenModel->editByID($dbToken['id'], $data);
        }

        \cache($platform . '-' . $token, json_encode($data), $this->login_expire);
        \cache($mobile, null);
        return $token;
    }

    public function deleteToken($member_id){
        $list = model('common/member/Token')->getList(['member_id'=>$member_id],0);
        foreach ($list as $v) \cache($v['platform'] . '-' . $v['token'],null);
        return true;
    }


    /**
     * User:Simony
     * Function: 获取token
     * @param $username
     * @return string
     */
    protected function createTokenVal($username)
    {
        $data = md5($username);
        $data = md5($data . time());
        $data = md5($data . randStr(5));
        return $data;
    }
}
